//
//  WTGiftListView.m
//  66TV
//
//  Created by ben on 16/8/8.
//  Copyright © 2016年 shifeng. All rights reserved.
//

#import "WTGiftListView.h"
#import "UIColor+WTExtend.h"
#import "Masonry.h"
#import "WTGiftService.h"
#import "WTLiveSDK.h"
#import "NSString+WTShowNumber.h"
#import "WTChatRoomGiftModel+Extend.h"
#import "WTGetCoinService.h"
#import "WTSendGiftManager.h"
#import "WTBarrageManager.h"

@interface WTGiftListView ()
@property (nonatomic, strong) UIScrollView* giftListScrollView;
@property (nonatomic, strong) UIView*       toolView;
@property (nonatomic, strong) UIView*       rechargeView;

@property (nonatomic, strong) WTGiftService*    giftService;
@property (nonatomic, strong) WTGetCoinService*    getCoinService;
@property (nonatomic, strong) NSMutableArray<WTPerGiftPageView *> *giftPageViews;
@end

@implementation WTGiftListView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        self.giftPageViews = [NSMutableArray arrayWithCapacity:0];
        
        [self setup];
    }
    return self;
}

#pragma mark - 
- (void)setup{
  
    self.giftListScrollView = ({
        UIScrollView* view = [[UIScrollView alloc] init];
        view.pagingEnabled = YES;
        view.bounces = NO;
        [self addSubview:view];
        view;
    });
    
    self.toolView = ({
        UIView* view = [[UIView alloc] init];
        view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
        [self addSubview:view];
        view;
    });
    
    self.sendButton = ({
        
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"送 出" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:12];
        button.layer.cornerRadius = 8;
        button.layer.masksToBounds = YES;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor themeColor]];
        [self.toolView addSubview:button];
        button;
    });
    
    
    self.rechargeView = ({
        UIView* view = [[UIView alloc] init];
        view.backgroundColor = [UIColor clearColor];
        [self.toolView addSubview:view];
        view;
    });
    
    self.leftpriceValueLabel = ({
        
        UILabel* label = [[UILabel alloc] init];
        label.text = [NSString stringWithFormat:@"%@%@",@"萝卜余额:",[NSString coinCount:@"123456"]];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor themeColor];
        [self.rechargeView addSubview:label];
        label;
    });
    
    self.rechargeButton = ({
        
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"充 值" forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitleColor:[UIColor themeColor] forState:UIControlStateNormal];
        [self.rechargeView addSubview:button];
        button;
    });

    
    
    [self layout];
}

- (void)layout{
    
    [self.giftListScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.and.trailing.and.top.mas_equalTo(0);
        make.bottom.mas_equalTo(-52);
    }];
    
    [self.toolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.and.trailing.and.bottom.mas_equalTo(0);
        make.height.mas_equalTo(52);
    }];
    
    
    [self.rechargeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.bottom.mas_equalTo(0);
        make.leading.mas_equalTo(10);
        make.trailing.mas_equalTo(self.rechargeButton.mas_trailing).offset(10);
    }];
    
    
    [self.leftpriceValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(0);
        make.centerY.mas_equalTo(self.rechargeView.mas_centerY);
    }];
    
    [self.rechargeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.leftpriceValueLabel.mas_trailing).offset(10);
        make.top.and.bottom.mas_equalTo(0);
        make.width.mas_equalTo(50);
    }];
    
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.trailing.mas_equalTo(-10);
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(self.toolView.mas_centerY);
    }];


    __weak __typeof(self)weakSelf = self;
    [self.giftService start:@{@"session_token":WTConfig.session_token} completionHandler:^(id responseObject, NSError *error) {
         [weakSelf handleGiftModels:responseObject];
    }];
    
    [self updateLeftCoin];
    
    //礼物扣完钱之后 需要更新一下本地金额
    [WTSendGiftManager sharedManager].updateLeftCoinBlock = ^(NSNumber* leftCoin){
      
        NSString* leftCoinString = [NSString stringWithFormat:@"%lld",[leftCoin longLongValue]];
        weakSelf.leftpriceValueLabel.text = [NSString stringWithFormat:@"%@%@",@"萝卜余额:",leftCoinString];
        weakSelf.leftCoinValue = leftCoin;
    };
    
    //弹幕扣完钱之后 需要更新一下本地金额
    [WTBarrageManager sharedManager].updateLeftCoinBlock = ^(NSNumber* leftCoin){
        
        NSString* leftCoinString = [NSString stringWithFormat:@"%lld",[leftCoin longLongValue]];
        weakSelf.leftpriceValueLabel.text = [NSString stringWithFormat:@"%@%@",@"萝卜余额:",leftCoinString];
        weakSelf.leftCoinValue = leftCoin;
    };
}


#pragma mark
- (void)handleGiftModels:(NSArray<WTGiftModel*>*)giftModels{
    
    NSMutableArray* chatRoomGiftModels = [NSMutableArray arrayWithCapacity:0];
    [giftModels enumerateObjectsUsingBlock:^(WTGiftModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [chatRoomGiftModels addObject:[obj chatRoomGiftModel]];
    }];
    
    [self.giftListScrollView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if([obj isKindOfClass:[WTPerGiftPageView class]]){
            [obj removeFromSuperview];
        }
    }];
    [self.giftPageViews removeAllObjects];
    
    NSMutableArray* tmpGifts = [[NSMutableArray alloc] init];
    [tmpGifts addObjectsFromArray:chatRoomGiftModels];
    
    NSInteger numsOfGiftPageView = 0;
    NSInteger count = giftModels.count;
    numsOfGiftPageView = count / 8;
    if(count % 8 != 0){
        numsOfGiftPageView++;
    }
    for(NSInteger i = 0; i < numsOfGiftPageView; i++){
        WTPerGiftPageView* view = [[WTPerGiftPageView alloc] init];
        [self.giftPageViews addObject:view];
        [self.giftListScrollView addSubview:view];
        
        NSInteger length = tmpGifts.count;
        if(tmpGifts.count < 8){
            length = tmpGifts.count;
        }else {
            length = 8;
        }
        NSArray* datas = [tmpGifts subarrayWithRange:NSMakeRange(0, length)];
        [tmpGifts removeObjectsInArray:datas];
        view.datas = datas;

    }
    
    for(NSInteger i = 0; i < numsOfGiftPageView; i++){
        WTPerGiftPageView* view = [self.giftPageViews objectAtIndex:i];
        if (i == 0) {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.giftListScrollView.mas_top);
                make.width.equalTo(self.giftListScrollView);
                make.height.equalTo(self.giftListScrollView);
                make.leading.mas_equalTo(self.giftListScrollView.mas_leading);
            }];
        }else {
            
            WTPerGiftPageView* preView = [self.giftPageViews objectAtIndex:i - 1];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(self.giftListScrollView.mas_top);
                make.width.equalTo(self.giftListScrollView);
                make.height.equalTo(self.giftListScrollView);
                make.leading.mas_equalTo(preView.mas_trailing);
            }];
        }
        
    }
    WTPerGiftPageView* lastView = [self.giftPageViews lastObject];
    [self.giftListScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(lastView.mas_trailing);
    }];
    
    
    __weak __typeof(self)weakSelf = self;
    [self.giftPageViews enumerateObjectsUsingBlock:^(WTPerGiftPageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        obj.perGiftSelectedBlock = ^(WTChatRoomGiftModel* model){
            
            model.selectedStatus = YES;
            [chatRoomGiftModels enumerateObjectsUsingBlock:^(WTChatRoomGiftModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if(obj != model){
                    obj.selectedStatus = NO;
                }
            }];
            [weakSelf.giftPageViews[idx] refresh];

            weakSelf.giftModel = model;
            
        };
    }];
}

- (void)updateLeftCoin{
    
    __weak __typeof(self)weakSelf = self;
    [self.getCoinService start:@{@"session_token":WTConfig.session_token} completionHandler:^(id responseObject, NSError *error) {
        
        NSNumber* totalNumber = responseObject;
        NSString* leftCoinString = [NSString stringWithFormat:@"%lld",[totalNumber longLongValue]];
        weakSelf.leftpriceValueLabel.text = [NSString stringWithFormat:@"%@%@",@"萝卜余额:",leftCoinString];
        
        weakSelf.leftCoinValue = totalNumber;
    }];
}


#pragma mark - getter
- (WTGiftService *)giftService{
    if(!_giftService){
        _giftService = [[WTGiftService alloc] init];
    }
    return _giftService;
}

- (WTGetCoinService *)getCoinService{
    if(!_getCoinService){
        _getCoinService = [[WTGetCoinService alloc] init];
    }
    return _getCoinService;
}
@end
